const EasyUpload = (function () {
    let self = {};

    self.init = function (url,
                          params,
                          fileName,
                          fileInputId,
                          successHandler,
                          errorHandler) {
        /*
         * 初始化上传
         * params:
         *  -url
         *  -params: json object
         *  -fileInputId
         *  -successHandler
         * */
        this.xhr = new XMLHttpRequest();
        this.formData = new FormData();

        this.url = url;
        this.params = $.extend({}, {}, params);
        this.fileName = fileName;
        this.fileInput = document.getElementById(fileInputId);
        this.otherFiles = [];
        this.successHandler = successHandler;
        this.errorHandler = errorHandler;

        this.setFormData();
    };

    self.setFormData = function () {
        $.each(this.params, function (key, value) {
            this.formData.append(key, value);
        }.bind(this));
    };

    self.addFile = function (name, fileInputId) {
        var length = this.otherFiles.length;
        this.otherFiles[length] = {name: name, fileInputId: fileInputId};
    };

    self.upload = function () {
        this.xhr.open("post", this.url);

        var file = this.fileInput.files[0];
        this.formData.append(this.fileName, file);

        for (var i = 0; i < this.otherFiles.length; i++) {
            var otherFileInput = document.getElementById(this.otherFiles[i].fileInputId);
            var otherFile = otherFileInput.files[0];
            this.formData.append(this.otherFiles[i].name, otherFile);
        }

        this.xhr.send(this.formData);
        this.response(this.xhr, this.successHandler, this.errorHandler);
    };

    self.response = function (xhr, successHandler, errorHandler) {
        xhr.onreadystatechange = function () {
            if (xhr.status == 200) {
                if (xhr.readyState == 4) {
                    var responseData = JSON.parse(xhr.responseText);
                    successHandler(responseData);
                }
            } else {
                if (errorHandler) {
                    var responseData = JSON.parse(xhr.responseText);
                    errorHandler(responseData);
                } else {
                    alert("请求失败！" + xhr.responseText);
                }
            }
        };
    };

    return self;
})();
export default EasyUpload;